<?php

class Application_Model_CommentMapper{
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Comment');
		}
		return $this->_dbTable;
	}
	public function save(Application_Model_Comment $com){
		$data = array(
			'author'	=> $com->getAuthor(),
			'text'		=> $com->getText(),
			'date'		=> $com->getDate(),
			'post'		=> $com->getPost()
		);
		
		if(null ===($id=$com->getId())){
			unset($data['id']);
			$data['date'] = new Zend_Db_Expr('NOW()');
			$this->getDbTable()->insert($data);
		}else{
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
	public function find($id, Application_Model_Comment $com){
		$result = $this->getDbTable()->findWithAuthor($id);
		if(count($result)==0){
			return;
		}
		$row = $result->current();
		$com	->setId($row->id)
				->setAuthor($row->author)
				->setDate($row->date)
				->setText($row->text)
				->setPost($row->post)
				->setPseudo($row->pseudo);
		return $com;
	}
	public function fetchAll($post){
		$resultSet = $this->getDbTable()->fetchAllWithAuthor($post);
		$entries = array();
		foreach($resultSet as $row){
			$entry = new Application_Model_Comment();
			$entry	->setAuthor($row->author)
					->setDate($row->date)
					->setId($row->id)
					->setPost($row->post)
					->setPseudo(($row->pseudo===null)?'Guest':$row->pseudo)
					->setText($row->text);
			$entries[] = $entry;
		}
		return $entries;
	}
}